package pers.vic.netty.echo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import pers.vic.netty.echo.server.handler.EchoServerHandler;

import java.net.InetSocketAddress;

/**
 * 描述:
 * @author Vic.xu
 * @date 2021-11-19 17:11
 */
public class EchoServer {

    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Usage " + EchoServer.class.getSimpleName() + " ");
        }
        //端口
        int port = Integer.parseInt(args[0]);
        //调用服务器的start方法
        new EchoServer(port).start();

    }

    private void start() throws Exception {
        final EchoServerHandler serverHandler = new EchoServerHandler();
        //1 创建 EventLoopGroup
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            //2 创建ServerBootstrap
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class) // 3 指定所使用的NIO传输Channel
                    .localAddress(new InetSocketAddress(port))//4 使用指定的端口设置套接字地址
                    .childHandler(new ChannelInitializer<SocketChannel>() {//5 添加一个EchoServerHandler到Channel的ChannelPipeline
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            //EchoServerHandler 被标注为@Shareable, 所以我们可以总是使用同样的实例
                            channel.pipeline().addLast(serverHandler);
                        }
                    });
            //6 异步绑定到服务器， 调用sync()方法阻塞等待直到绑定完成
            ChannelFuture f = bootstrap.bind().sync();
            //7 获取Channel的CloseFuture, 并且阻塞当前线程直到它完成
            f.channel().closeFuture().sync();
        }finally {
            // 8 关闭EventLoopGroup 释放所有资源
            group.shutdownGracefully().sync();

        }
    }
}
